<template>
  <div>
    <h1>订单列表</h1>
    <div>
      <el-form :inline="true" :model="searchOrder" class="demo-form-inline">
        <el-form-item label="关键词">
          <el-input
            v-model="searchOrder.keyWord"
            placeholder="商品名称/ID/关键词"
            clearable
          />
        </el-form-item>
        <el-form-item label="订单状态">
          <el-select
            v-model="searchOrder.status"
            placeholder="请选择订单状态"
            clearable
            style="width: 150px"
          >
            <el-option label="未支付" :value="0" />
            <el-option label="已支付" :value="1" />
            <el-option label="待发货" :value="2" />
          </el-select>
        </el-form-item>
        <el-form-item label="订单类型">
          <el-select
            v-model="searchOrder.orderType"
            placeholder="请选择订单状态"
            clearable
            style="width: 150px"
          >
            <el-option label="普通订单" :value="1" />
            <el-option label="秒杀订单" :value="2" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="loadList">查询</el-button>
          <el-button type="primary" @click="onAddOrder">添加订单</el-button>
          <el-button type="success" @click="onExPortOrder">导出订单</el-button>
          <el-button type="danger" @click="deleteByOrder">批量删除</el-button>
        </el-form-item>
      </el-form>
    </div>
    <div>
      <el-table
        :data="tableData"
        style="width: 100%"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="orderId" label="ID" />
        <el-table-column prop="orderNo" label="订单编号" />
        <el-table-column prop="prodInfo" label="商品信息" />
        <el-table-column prop="orderAmount" label="订单金额" />
        <el-table-column prop="createTime" label="创建时间" />
        <el-table-column prop="createBy" label="消费者" />
        <el-table-column prop="orderStatus" label="订单状态">
          <template #default="scope">
            <el-tage v-if="scope.row.orderStatus == 0">未支付</el-tage>
            <el-tage v-if="scope.row.orderStatus == 1">已支付</el-tage>
            <el-tage v-if="scope.row.orderStatus == 2">待发货</el-tage>
          </template>
        </el-table-column>
        <el-table-column prop="" label="商品图片">
          <template #default="scope">
            <img
              v-for="item in scope.row.imageList"
              :src="item"
              width="50"
              height="50"
            />
          </template>
        </el-table-column>
        <el-table-column label="操作"></el-table-column>
      </el-table>

      <div class="demo-pagination-block">
        <el-pagination
          v-model:current-page="searchOrder.pageNum"
          v-model:page-size="searchOrder.pageSize"
          :page-sizes="[2, 4, 6, 8]"
          :size="size"
          :disabled="disabled"
          :background="background"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>
    <div>
      <el-dialog v-model="dialogFormVisible" title="新增订单" width="800">
        <el-form :model="form">
          <el-form-item label="选择商品" :label-width="formLabelWidth">
            <el-select v-model="form.infoId" placeholder="请选择要购买的商品">
              <el-option
                v-for="item in prodInfoList"
                :label="item.prodName"
                :value="item.infoId"
                :key="item.infoId"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="购买数量" :label-width="formLabelWidth">
            <el-input v-model="form.buyNum" autocomplete="off" />
          </el-form-item>
          <div>
            <el-button type="primary" @click="addprodInfo">添加</el-button>
          </div>
          <div>
            <el-table :data="buyInfoList" stripe style="width: 100%">
              <el-table-column prop="prodId" label="商品ID" />
              <el-table-column prop="prodName" label="商品名称" />
              <el-table-column prop="prodPrice" label="商品价格" />
              <el-table-column prop="buyNum" label="购买数量" />
              <el-table-column label="操作">
                <template #default="scope">
                  <el-button
                    size="small"
                    type="danger"
                    @click="onDeleteProdInfo(scope.row)"
                  >
                    删除
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
          </div>
          <div>总价:{{ totalAmount }}元</div>
        </el-form>
        <template #footer>
          <div class="dialog-footer">
            <el-button @click="dialogFormVisible = false">取消</el-button>
            <el-button type="primary" @click="onSubmitAddOrder">
              添加订单
            </el-button>
          </div>
        </template>
      </el-dialog>
    </div>
  </div>
</template>
<script lang="ts" setup>
import { onMounted, ref } from "vue";
import { ElMessage, ElMessageBox, type ComponentSize } from "element-plus";
import {
  getOrderList,
  getProdInfoList,
  addOrder,
  deleteOrder,
} from "../api/api";
const dialogFormVisible = ref(false);
const formLabelWidth = "140px";

const form = ref({
  infoId: null,
  buyNum: 1,
});

const tableData = ref([]);
const searchOrder = ref({
  pageNum: 1,
  pageSize: 2,
  keyWord: "",
  orderType: null,
  status: null,
});
const total = ref(0);

const size = ref<ComponentSize>("default");
const background = ref(false);
const disabled = ref(false);

const handleSizeChange = (val: number) => {
  console.log(`${val} items per page`);
  searchOrder.value.pageSize = val;
  loadList();
};
const handleCurrentChange = (val: number) => {
  console.log(`current page: ${val}`);
  searchOrder.value.pageNum = val;
  loadList();
};

const loadList = () => {
  getOrderList(searchOrder.value).then((res) => {
    if (res.data.code == 200) {
      tableData.value = res.data.data.records;
      total.value = res.data.data.total;
    }
  });
};

const prodInfoList = ref([]);
const buyInfoList = ref([]);
const totalAmount = ref(0);

//添加商品到购物车
const addprodInfo = () => {
  prodInfoList.value.forEach((item) => {
    if (item.infoId === form.value.infoId) {
      item.buyNum = form.value.buyNum;
      buyInfoList.value.push(item);
    }
  });

  //动态计算总价
  totalAmount.value = 0.0;
  buyInfoList.value.forEach((item) => {
    totalAmount.value += item.prodPrice * item.buyNum;
  });
};

//删除小订单
const onDeleteProdInfo = (row: any) => {
  buyInfoList.value.forEach((item, index) => {
    if (item.infoId === row.infoId) {
      buyInfoList.value.splice(index, 1);
    }
  });

  //动态计算总价
  totalAmount.value = 0.0;
  buyInfoList.value.forEach((item) => {
    totalAmount.value += item.prodPrice * item.buyNum;
  });
};

//添加对话框
const onAddOrder = () => {
  buyInfoList.value = [];
  form.value = {
    infoId: null,
    buyNum: 1,
  };
  totalAmount.value = 0.0;
  dialogFormVisible.value = true;
};

//提交订单
const onSubmitAddOrder = () => {
  addOrder(buyInfoList.value).then((res) => {
    if (res.data.code == 200) {
      ElMessage.success("订单添加成功");
      dialogFormVisible.value = false;
      loadList();
    } else {
      ElMessage.error(res.data.msg);
    }
  });
};

//导出
const onExPortOrder = () => {
  let url = "http://localhost:9011/prod/order/exportOrderList/1";
  window.open(url);
};

const multipleSelection = ref<any[]>([]);

const handleSelectionChange = (val: any[]) => {
  multipleSelection.value = val;
  console.log("handleSelectionChange", multipleSelection.value);
};
//批量删除
const deleteByOrder = () => {
  let ids = [];
  //参数检查
  if (multipleSelection.value.length == 0) {
    ElMessage.error("请选择要删除取得商品");
    return;
  }

  multipleSelection.value.forEach((item) => {
    ids.push(item.orderId);
  });

  ElMessageBox.confirm("删除后无法恢复，确认删除吗?", "警告", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(() => {
      //确认删除
      deleteOrder(ids).then((res) => {
        if (res.data.code == 200) {
          ElMessage.success("删除成功");
          loadList();
        } else {
          ElMessage.error(res.data.msg);
        }
      });
    })
    .catch(() => {
      //取消删除
    });
};

onMounted(() => {
  loadList();

  //获取商品信息列表
  getProdInfoList().then((res) => {
    if (res.data.code == 200) {
      prodInfoList.value = res.data.data;
    }
  });
});
</script>
